#encoding:utf-8
import os
import string
import logging
import threading
import queue
import re
import optparse

'''
    查找线程
'''
class QueueSearcher(threading.Thread):
    def __init__(self, workQueue, regexKey, idNo):
        super().__init__()
        self.workQueue = workQueue
        self.regexKey = regexKey
        self.idNo = idNo
        self.partten = re.compile(regexKey)
    def run(self):
        while True:
            try:
                fileName = self.workQueue.get()
                self.process(fileName)
            finally:
                self.workQueue.task_done()
    def process(self, fileName):
        f = open(fileName, 'r', encoding = 'utf-8')
        strs = f.readlines()
        line = 0
        for s in strs:
            line += 1
            if self.partten.search(s) != None:
                print('FIND->'+ fileName + ' line :' + str(line) 
                    + '\n\t' + s)
                break
        f.close()
'''
    主函数
'''
def main():
    opts, paths = parse_options()
    print(opts)
    print(paths)
    workQueue = queue.PriorityQueue()
   
    for i in range(1, opts.process + 1):
        worker = QueueSearcher(workQueue, opts.regex, i)
        worker.daemon = True
        worker.start()
    num = 0
    for path in paths:
        if not os.path.exists(path):
            print(path + '路径不存在')
        for root,dirs,files in os.walk(path):
            for filespath in files:
                num += 1
                filePath = os.path.join(root,filespath)
                workQueue.put(filePath)
    print('total ' + str(num) + 'files')
    workQueue.join()
    print('Process Done.')
    
'''
    选项解析
'''
def parse_options():
    parser = optparse.OptionParser(
            usage=('用法: %prog [选项] [路径1] [路径2]\n'
                   '在指定文件夹中查找包含某字符串的文件\n'
                   '%prog -h 获取帮助\n'))                  
    parser.add_option('-r', '--regex', dest='regex', action='store', help='查找正则表达式')
    parser.add_option('-o', '--output', dest='output',default='output.txt', action='store', help='输出到文件中')
    parser.add_option('-f', '--full', dest='full', default=False, action='store_true', help='指定全文搜索')
    parser.add_option('-p', '--process', type='int', dest='process', default=5, action='store', help='指定线程数')
    parser.add_option('-t', '--time', dest='time', default=False, action='store_true', help='统计执行时间')
    opts, args = parser.parse_args()
    while len(args) == 0:
        file = input('请指定查找文件夹\n')
        args = file.split()
    while opts.regex == None or opts.regex == '':
        opts.regex = input('请指定查找字符串,支持正则').lstrip().rstrip()
    return opts, args
if __name__ == '__main__':
    main()
